package net.digitalartwork.mp3player {
	import flash.display.MovieClip;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	import flash.net.URLLoader;
	import flash.events.ErrorEvent;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;
	//--------------------------------------------------------------------------
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.media.SoundLoaderContext;
	import flash.media.SoundMixer;
	//--------------------------------------------------------------------------
	import gs.TweenFilterLite;
	import gs.OverwriteManager;
	import gs.easing.*;
	//--------------------------------------------------------------------------
	import net.digitalartwork.mp3player.PlayPauseBtn;
	import net.digitalartwork.mp3player.ProgressBar;
	//--------------------------------------------------------------------------
	
	public class DAMp3Player extends MovieClip {
		
		//--------------------------------------------------------------------------
		// ASSETS
		//--------------------------------------------------------------------------
		public var scrub_mc:MovieClip;
		public var bar_mc:ProgressBar;
		public var playpause_btn:PlayPauseBtn;
		public var credit_text:TextField;
		public var speaking_text:TextField;
		public var time_text:TextField;
		//--------------------------------------------------------------------------
		// DISPATCH
		//--------------------------------------------------------------------------
		public var MOUSECLICK:String = "mousedown";
		public var ON_MP3START:String = "onmp3start";
		public var ON_MP3NEWAUDIO:String = "onmp3newaudio";
		public var ON_PLAY:String = "toggleplay";
		public var ON_PAUSE:String = "togglepause";
		//--------------------------------------------------------------------------
		// PROPERTIES
		//--------------------------------------------------------------------------
		public var _w:Number;
		public var _h:Number;
		public var _barwidth:Number = 150;
		//--------------------------------------------------------------------------
		// AUDIO
		//--------------------------------------------------------------------------
		private var audiotimer:Timer = new Timer(20);
		
		private var _channel:SoundChannel;
		private var _sound:Sound;
		private var _position:int;
		private var _length:int;
		private var _loaded:int;
		private var _total:int;
		private var _currentPosition:int;
		private var _buffer:SoundLoaderContext;
		private var _urlloader:URLLoader;
		
		private var _minutes:Number;
		private var _seconds:Number;
		
		private var _playing:Boolean = false;
		private var _loading:Boolean = false;
		private var _firstload:Boolean = false;
		
		private var _mp3file:String = "test.mp3";
		//--------------------------------------------------------------------------
		// VISUALIZER
		//--------------------------------------------------------------------------
		private var ba:ByteArray = new ByteArray();
		
		//--------------------------------------------------------------------------
		
		public function DAMp3Player() {
			trace("ProgressBar Init");
			//--------------------------------------------------------------------------
			// 
			//--------------------------------------------------------------------------


			//--------------------------------------------------------------------------
			// INIT STATES
			//--------------------------------------------------------------------------
			//credit_text.text = "";
			credit_text.alpha=0;
			
			speaking_text.autoSize = "left";
			credit_text.autoSize = "left";
			
			bar_mc.alpha=0;
			//speaking_text.alpha = 0;
			//--------------------------------------------------------------------------
			// LISTENERS
			//--------------------------------------------------------------------------
			playpause_btn.addEventListener(playpause_btn.TOGGLE_PLAY, onTogglePlay); 
			playpause_btn.addEventListener(playpause_btn.TOGGLE_PAUSE, onTogglePause);
			//--------------------------------------------------------------------------
			audiotimer.addEventListener(TimerEvent.TIMER, onAudioTimer);
			//--------------------------------------------------------------------------
			bar_mc.addEventListener(bar_mc.ON_SCRUB, onScrub);
			bar_mc.addEventListener(bar_mc.ON_SCRUB_DONE, onScrubDone);
			//--------------------------------------------------------------------------
			scrub_mc.mouseEnabled = false;
			scrub_mc.mouseChildren = false;
			scrub_mc.alpha=0;
			//--------------------------------------------------------------------------
			newAudio(_mp3file, "", "")
		}
		
		public function visualizer():void {
			var hh:Number = (bar_mc._h/2)
			bar_mc.visualizer_mc.graphics.clear();
			//bar_mc.visualizer_mc.graphics.lineStyle(.5, 0xFFFFFF);
			
			//bar_mc.visualizer_mc.graphics.beginFill(0x6A87AA);
			bar_mc.visualizer_mc.graphics.beginFill(0x222222);
			

			SoundMixer.computeSpectrum(ba, true);
			for(var i:uint=0; i<(bar_mc._w/2); i++) {
				var num:Number = -ba.readFloat()*hh  + (hh+3);

				bar_mc.visualizer_mc.graphics.lineTo(i*2, num);
			}
			bar_mc.visualizer_mc.graphics.lineTo(bar_mc._w, bar_mc._h);
			bar_mc.visualizer_mc.graphics.lineTo(0, bar_mc._h);
			bar_mc.visualizer_mc.graphics.lineTo(0, hh);

		}

		public function newAudio(mp3URL:String="", ct:String="", st:String=""):void {
			if (_playing == true) {
				audiopause();
			}
			
			time_text.text = "0:00";
			
			_firstload = false;
			_mp3file = mp3URL;
			_currentPosition = 0;
			
			
			credit_text.text = ct;
			credit_text.alpha=0;
			speaking_text.text = st;
			
			TweenFilterLite.to(bar_mc, .5, {width:1, alpha:0, ease:Linear.easeOut});
			TweenFilterLite.to(speaking_text, .5, {x:57, alpha:1, ease:Linear.easeOut});
			TweenFilterLite.to(credit_text, .5, {x:57 + speaking_text.textWidth + 5, alpha:0, ease:Linear.easeOut});
			TweenFilterLite.to(time_text, .5, {x:57, alpha:1, ease:Linear.easeOut});
			TweenFilterLite.to(scrub_mc, .5, {alpha:0, ease:Linear.easeOut});
			
			_w = 57 + speaking_text.textWidth;
			
			dispatchEvent(new Event(ON_MP3NEWAUDIO));
			
		}
		
		public function audioplay():void {
			if (!_firstload) {
				
				if (credit_text.text == "") {
					speaking_text.text = "";
				} else {
					speaking_text.text = "Now Speaking";
				}
				
				TweenFilterLite.to(bar_mc, .5, {width:_barwidth, alpha:1, ease:Linear.easeOut});
				TweenFilterLite.to(speaking_text, .5, {x:scrub_mc.x + _barwidth + 10, alpha:1, ease:Linear.easeOut});
				TweenFilterLite.to(credit_text, .5, {x:scrub_mc.x + _barwidth + 10 + speaking_text.textWidth + 5, alpha:1, ease:Linear.easeOut});
				TweenFilterLite.to(time_text, .5, {x:scrub_mc.x + _barwidth + 10, alpha:1, ease:Linear.easeOut});
				TweenFilterLite.to(scrub_mc, .5, {alpha:1, ease:Linear.easeOut});
				

				trace("readyToPlay")
				_buffer = new SoundLoaderContext(5000);
				_sound = new Sound(new URLRequest(_mp3file), _buffer);
				_channel = _sound.play();
				_sound.addEventListener(Event.ID3, onID3);
				_playing = true;
				_loading = true;
				_firstload = true;

				audiotimer.addEventListener(TimerEvent.TIMER, onAudioTimer);
				audiotimer.start();

				_w = scrub_mc.x + _barwidth + 10 + speaking_text.textWidth +5 + credit_text.textWidth;

				
				dispatchEvent(new Event(ON_MP3START));
				//scrub_mc.alpha=1;
				

				
				
			} else {
				_channel = _sound.play(_currentPosition);
				_playing = true;
			}
			
		}
		
		private function togglePlay(e:Event):void {
			if (!_firstload) {
				_buffer = new SoundLoaderContext(5000);
				_sound = new Sound(new URLRequest(_mp3file), _buffer);
				_channel = _sound.play();
				_sound.addEventListener(Event.ID3, onID3);
				_playing = true;
				_firstload = true;
				
			} else {
				
			}
			
			if (_playing == true) {
				// If playing, stop and save that position
				_position = _channel.position;
				_channel.stop();
				_playing = false;
				_currentPosition = _position;
			} else {
				// Else, start at the saved position
				_channel = _sound.play(_currentPosition);
				_playing = true;
			}

		}
		
		public function audiopause():void {
			trace(_channel.position)
			_position = _channel.position;
			_channel.stop();
			_playing = false;
			_currentPosition = _position;
		}
		
		private function onTogglePlay(e:Event):void {
			trace("onTogglePlay");
			audioplay();
			dispatchEvent(new Event(ON_PLAY));
		}
		
		private function onTogglePause(e:Event):void {
			trace("onTogglePause");
			audiopause();
			dispatchEvent(new Event(ON_PAUSE));
		}
		
		private function onID3(e:Event):void {
			trace(_sound.id3.artist);
			trace(_sound.id3.songName);
			trace(_sound.id3.artist);
		}
		
		private function onAudioTimer(e:TimerEvent):void {
			_loaded = _sound.bytesLoaded;
			_total = _sound.bytesTotal;
			_length = _sound.length;
			_position = _channel.position;
			
			
			
			if (_total > 0) {
				// if mp3 is successfully loaded
				
				if (_loaded < _total) {
					_loading = true;
				} else {
					_loading = false;
				}
				
				bar_mc.loadprogress_mc.width = Math.round(100 * _loaded / _total);
				
				if (_playing) {
					
					//bar_mc.progress_mc.width = Math.round(100 * _position / _length);
					
					updateTimeDisplay();
					visualizer();
				} else {
					
				}
				
			}
		}
		
		private function updateTimeDisplay():void {
			
			bar_mc.progress_mc.width = (100 * _position / _length);
			scrub_mc.x = bar_mc.x + (bar_mc.progress_mc.width * bar_mc.scaleX);
			
			
			_minutes = Math.floor(_position / 1000) / 60 >> 0;
			_seconds = Math.floor(_position / 1000) % 60 >> 0;

			if ( _seconds >= 0 && _seconds < 10) {
				time_text.text = _minutes.toString() + ":0" + _seconds.toString();
			} else {
				time_text.text = _minutes.toString() + ":" + _seconds.toString();
			}
		}
		
		private function onScrub(e:Event):void {
			audiotimer.stop();
			
			_position =  bar_mc._percent *_length;
			_channel.stop();
			_channel = _sound.play(_position);
			
			
			updateTimeDisplay();
		}
		
		private function onScrubDone(e:Event):void {
			audiotimer.start();
			
		}
		
		
	}
	
}